var map = null;
var geocoder;
var base_url;//= "http://localhost/cellplan/";
var site_url;//= "http://localhost/cellplan/index.php/";

var polyPathdesa = [];
var polyPathkec = [];
var poly_layer_budidaya = [];
var kecPath=[];
var kelPath=[];


var polyHoverDes = [];
var polyHoverkec = [];

var bound_kec = [];

var layer = [];


google.maps.event.addDomListener(window, 'load', initialize);
var infoWindow;

//var markers_tower = [];


function initialize() {
    base_url = document.getElementById("base_url").value;
    site_url = document.getElementById("site_url").value;
    infoWindow = new google.maps.InfoWindow();
    var myOptions = {
        zoom: 10,
        center: new google.maps.LatLng(-8.219021, 114.369105),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: true,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
            position: google.maps.ControlPosition.BOTTOM_LEFT
        },
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.LARGE,
            position: google.maps.ControlPosition.LEFT_BOTTOM
        },
        panControl: true,
        panControlOptions: {
            position: google.maps.ControlPosition.LEFT_BOTTOM
        },
        streetViewControl: false

    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    //draw_poly_kab();
    draw_poly_kec();
    draw_poly_desa();  
    layer["lindung"] = new google.maps.FusionTablesLayer({
              map: map,
              heatmap: { enabled: false },
              query: {
                select: "col5",
                from: "1QxBQ271_oAH_D3Vb3HgDMUGe---I85zzPNriSJEY",
                where: ""
              },
              options: {
                styleId: 2,
                templateId: 2
              }
            });
    
    $('.strategis').change(function() {
           add_layer_strategis();
    });

    $('.budidaya').change(function() {
            add_layer_budidaya();
    });

    $('.lindung').change(function() {
            add_layer_lindung();
    });
    
    $('.cluster').change(function() {
            add_layer_cluster();
    });
    
    $('.jalan').change(function() {
        if (this.checked) {
           add_layer_jalan(); 
        } else {
            layer["jalan"].setMap(null);
        }
    });
    
    $('.pariwisata').change(function() {
        if (this.checked) {
            add_layer_pariwisata(); 
        } else {
            layer["pariwisata"].setMap(null);
        }
    });
    
    $('.siskot').change(function() {
        if (this.checked) {
           add_layer_siskot(); 
        } else {
            layer["siskot"].setMap(null);
        }
    });
    
    
    $('#kecbox').change(function() {
        if (this.checked) {
            clear_layer_all(kecPath);
            draw_poly_kec(); 
        } else {
            clear_layer_all(kecPath);
        }
    });

    $('#desabox').change(function() {
        if (this.checked) {
            clear_layer_all(kelPath);
            draw_poly_desa();
        } else {
           clear_layer_all(kelPath);
        }
    });
    
    $('#pilihkecamatan').change(function() {
        var id = $('#pilihkecamatan option:selected').val();  
        document.getElementById("id_kec").value = id;
        clear_layer_all(kecPath);
        draw_poly_kec();
        map.fitBounds(bound_kec[id]);
    });
}

function add_layer_jalan(){
    if(layer["jalan"])layer["jalan"].setMap(null);
    layer["jalan"] = new google.maps.FusionTablesLayer({
      map: map,
      heatmap: { enabled: false },
      query: {
        select: "col4",
        from: "1TCAcL8Y-DNkKs9Wm2PP14C_oX_ElFfWrK6C1n_MZ",
        where: ""
      },
      options: {
        styleId: 2,
        templateId: 2
      }
    });
}

function add_layer_pariwisata(){
    if(layer["pariwisata"])layer["pariwisata"].setMap(null);
    layer["pariwisata"] = new google.maps.FusionTablesLayer({
       map: map,
        heatmap: { enabled: false },
        query: {
          select: "col6",
          from: "1GxNv2fXDDhllStP0APYjn2GxNDCuwTpftpLpenvR",
          where: ""
        },
        options: {
          styleId: 2,
          templateId: 2
        }
      });
}

function add_layer_siskot(){
    if(layer["siskot"])layer["siskot"].setMap(null);
    layer["siskot"] = new google.maps.FusionTablesLayer({
    map: map,
    heatmap: { enabled: false },
    query: {
      select: "col6",
      from: "1RgBS2cxTqIySfa1jkbqKWW6J-2Y1eStU-pDdh2C6",
      where: ""
    },
    options: {
      styleId: 2,
      templateId: 2
    }
  });
}

function add_layer_budidaya(){
        var selek = "";
        if ($('.budidaya:checked').length) {
          var chkId = '';
          $('.budidaya:checked').each(function () {
            chkId += $(this).val() + ",";
          });
          chkId = chkId.slice(0, -1);
          selek = chkId;
        
          if(layer["budidaya"])layer["budidaya"].setMap(null);
        
            layer["budidaya"] = new google.maps.FusionTablesLayer({
              map: map,
              heatmap: { enabled: false },
              query: {
                select: "col3\x3e\x3e0",
                from: "1Fezz-bLpT-Zdk44LxTk8C3t6Au-jEqvz34R_fG2U",
                where: "Number IN ("+selek+")"
              },
               options: {
                styleId: 2,
                templateId: 2
              }
            });  
        }
        else {
          layer["budidaya"].setMap(null);
        }    
    }
    
    function add_layer_strategis(){
        var selek = "";
        if ($('.strategis:checked').length) {
          var chkId = '';
          $('.strategis:checked').each(function () {
            chkId += $(this).val() + ",";
          });
          chkId = chkId.slice(0, -1);
          selek = chkId;
        
          if(layer["strategis"]) layer["strategis"].setMap(null);
                layer["strategis"] = new google.maps.FusionTablesLayer({
                map: map,
                heatmap: { enabled: false },
                query: {
                  select: "col4",
                  from: "1TWCWnpsjQDNjIyM9KSg-DWtmoF3qeqZAA5Exjl_n",
                  where: "no_layer IN ("+selek+")"
                },
                options: {
                  styleId: 2,
                  templateId: 2
                }
          });
        }
        else {
          layer["strategis"].setMap(null);
        }    
    }
    
function add_layer_lindung(){
    var selek = "";
    if ($('.lindung:checked').length) {
      var chkId = '';
      $('.lindung:checked').each(function () {
        chkId += $(this).val() + ",";
      });
      chkId = chkId.slice(0, -1);
      selek = chkId;

      if(layer["lindung"]) layer["lindung"].setMap(null);
            layer["lindung"] = new google.maps.FusionTablesLayer({
              map: map,
              heatmap: { enabled: false },
              query: {
                select: "col5",
                from: "1QxBQ271_oAH_D3Vb3HgDMUGe---I85zzPNriSJEY",
                where: "layer_id IN ("+selek+")"
              },
              options: {
                styleId: 2,
                templateId: 2
              }
            });
    }
    else {
      layer["lindung"].setMap(null);
    }    

}

function add_layer_cluster(){
    var selek = "";
    if ($('.cluster:checked').length) {
      var chkId = '';
      $('.cluster:checked').each(function () {
        chkId += $(this).val() + ",";
      });
      chkId = chkId.slice(0, -1);
      selek = chkId;

      if(layer["cluster"]) layer["cluster"].setMap(null);
       layer["cluster"] = new google.maps.FusionTablesLayer({
            map: map,
            heatmap: { enabled: false },
            query: {
              select: "col6",
              from: "10NEI8jUhyGs9SZECJbwdAbr5Vy4Xh5IKZef3evSM",
              where: "id_layer IN ("+selek+")"
            },
            options: {
              styleId: 2,
              templateId: 2
            }
      });
    }
    else {
      layer["cluster"].setMap(null);
    }    

}


function add_polygon_desa(poly_data_lgkp, index) {
    var titik_poly = [];
    var point_label;


    var poly_data = poly_data_lgkp.DESA_POINT_LIST;
    for (var a = 0; a < poly_data.length - 1; a++) {
        titik_poly[a] = new google.maps.LatLng(poly_data[a].LAT, poly_data[a].LNG);
    }
    var bounds = new google.maps.LatLngBounds();
    for (i = 0; i < titik_poly.length; i++) {
        bounds.extend(titik_poly[i]);
    }

    kelPath[index] = new google.maps.Polyline({
        path: titik_poly,
        strokeColor: '#0c6715',
        strokeOpacity: 0.6,
        strokeWeight: 0.4
      });
    kelPath[index].setMap(map);
}

function clear_layer_all(path) {
    if (path) {
        for (i in path) {
            path[i].setMap(null);
        }
    }
}

function draw_poly_desa() {
    var id_kec = 0;// = document.getElementById("id_kec").value;
    $.ajax({
        type: "POST",
        url: site_url + "/map/get_polygon_desa/"+id_kec,
        dataType: 'json',
        success: function(json) {
            if (json.Desa.length > 0) {
                for (var i = 0; i < json.Desa.length; i++) {
                    var point_des = json.Desa[i];
                    add_polygon_desa(point_des, i);
                }
            }
        }
    });
    return false;
}

function add_polygon_kec(poly_data_lgkp){
    var titik_poly = [];
    var point_label;

    var poly_data = poly_data_lgkp.KEC_POINT_LIST;
    var index = poly_data_lgkp.KEC_KODE;
    
    for (var a = 0; a < poly_data.length - 1; a++) {
        titik_poly[a] = new google.maps.LatLng(poly_data[a].LAT, poly_data[a].LNG);
    }
    
    bound_kec[index] = new google.maps.LatLngBounds();
    for (i = 0; i < titik_poly.length; i++) {
        bound_kec[index].extend(titik_poly[i]);
    }
    kecPath[index] = new google.maps.Polyline({
        path: titik_poly,
        strokeColor: '#333333',
        strokeOpacity: 0.8,
        strokeWeight: 1.5
      });
    kecPath[index].setMap(map);

}

function draw_poly_kec() {
    var id_kec = document.getElementById("id_kec").value;
    $.ajax({
        type: "POST",
        url: site_url + "/map/get_polygon_kec/" + id_kec,
        dataType: 'json',
        success: function(json) {
            //alert(json.Desa.length);
            if (json.Desa.length > 0) {
                for (var i = 0; i < json.Desa.length; i++) {
                    var point_kec = json.Desa[i];
                    add_polygon_kec(point_kec);
                }
            }
        }
    });
    return false;
}

function draw_poly_kab() {
    $.ajax({
        type: "POST",
        url: site_url + "/map/get_polygon_kab",
        dataType: 'json',
        success: function(json) {
            //alert(json.Desa.length);
            if (json.KAB.length > 0) {
                for (var i = 0; i < json.KAB.length; i++) {
                    var point_kec = json.KAB[i];
                    add_polygon_kab(point_kec);
                }
            }
        }
    });
    return false;
}

function add_polygon_kab(poly_data_lgkp){
    var titik_poly = [];
    var point_label;

    var poly_data = poly_data_lgkp.GEO;
    
    
    for (var a = 0; a < poly_data.length - 1; a++) {
        titik_poly[a] = new google.maps.LatLng(poly_data[a].LAT, poly_data[a].LNG);
    }

    var kab = new google.maps.Polyline({
        path: titik_poly,
        strokeColor: '#333333',
        strokeOpacity: 0.8,
        strokeWeight: 1.5
      });
    kab.setMap(map);

}
    